import 'package:auto_size_text/auto_size_text.dart';
import 'package:distribution_mall_flutter/assets.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/image_constant.dart';
import 'package:distribution_mall_flutter/pages/home/home_provider.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/home_goods/home_goods_provider.dart';
import 'package:distribution_mall_flutter/provider/common/tab.dart';
import 'package:distribution_mall_flutter/provider/home/waterfall.dart';
import 'package:distribution_mall_flutter/utils/image_loader.dart';
import 'package:distribution_mall_flutter/widgets/cross_scroll.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final List<String> tabName = [
  'Top Sellers',
  'Hair Care',
  'Oral Care',
  'Body Care',
  'Personal Care',
  'Der.J Zone',
  'Scoban Zone',
  'Nykaa Zone',
];

final List<String> imgList = [
  Assets.assets_icons_tabbar_top_sellers_png,
  Assets.assets_icons_tabbar_hair_care_png,
  Assets.assets_icons_tabbar_oral_care_png,
  Assets.assets_icons_tabbar_body_care_png,
  Assets.assets_icons_tabbar_personal_care_png,
  Assets.assets_icons_tabbar_der_zone_png,
  Assets.assets_icons_tabbar_scoban_zone_png,
  Assets.assets_icons_tabbar_nykaa_zone_png
];

class HomeTab extends ConsumerStatefulWidget {
  final double wrapperHeight;
  final TabController homeTabController;

  const HomeTab(
      {super.key,
      required this.wrapperHeight,
      required this.homeTabController});

  @override
  ConsumerState createState() => _HomeTab();
}

class _HomeTab extends ConsumerState<HomeTab> with TickerProviderStateMixin {
  late final AnimationController _animationController;
  late final Animation<double> _animation;

  @override
  void initState() {
    super.initState();

    ///这里可以不用remove 和整个app生命周期一致
    widget.homeTabController.addListener(() {
      int index = widget.homeTabController.index;
      ref.read(tabProvider.notifier).tabIndex(index);
    });

    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
    _animation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(_animationController);
  }

  Widget renderTab(String item, bool isActive, int index) {
    return Tab(
      height: 35,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.fromLTRB(9, 0, 9, 0),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16.8),
              border: Border.all(
                color: isActive
                    ? Colors.white
                    : const Color.fromRGBO(230, 230, 234, 1),
                width: 0.9,
              ),
            ),
            child: Text(item),
          ),
          Visibility(
              visible: index == 0,
              child: Positioned(
                top: -10,
                right: 0,
                child: ImageLoader.imageAsset(ImageLocalConstant.homeNew),
                width: 23,
                height: 20,
              ))
        ],
      ),
    );
  }

  void tabTrigger(index, tabModal, categoryModal) {
    if (index == tabModal.activeIndex) return;
    ref
        .read(homeGoodsProvider(tabName[index]).notifier)
        .refreshData(tabName[index]);
    ref.read(tabProvider.notifier).tabIndex(index);
  }

  @override
  Widget build(BuildContext context) {
    var isTab = ref.watch(homeIsTabProvider);
    final tabModal = ref.watch(tabProvider);
    // ref.listen(tabProvider, (pre, next) {
    //   if (pre?.tabSlide == next.tabSlide || next.tabSlide == null) return;
    //   ref
    //       .read(tabProvider.notifier)
    //       .changeConIndex(next.tabSlide, widget.homeTabController);
    // });

    return AnimatedSwitcher(
        duration: Duration(milliseconds: isTab == true ? 100 : 100),
        transitionBuilder: (Widget child, Animation<double> animation) {
          //执行缩放动画
          return FadeTransition(
            opacity: animation,
            child: child,
          );
        },
        child: isTab == true
            ? Container(
                key: const ValueKey("home_tab_true"),
                height: widget.wrapperHeight,
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.only(left: 11),
                child: SizedBox(
                  height: 45,
                  child: TabBar(
                    controller: widget.homeTabController,
                    onTap: (index) {
                      ref
                          .read(tabProvider.notifier)
                          .changeTab(index, tabName: tabName[index]);
                      // tabTrigger(index, tabModal, categoryModal);
                    },
                    padding: const EdgeInsets.only(top: 9),
                    tabAlignment: TabAlignment.start,
                    labelStyle: const TextStyle(
                        fontSize: FontConstant.f137,
                        fontWeight: FontWeight.bold,
                        color: Colors.white),
                    unselectedLabelStyle: const TextStyle(
                      color: ColorConstant.black21,
                      fontSize: FontConstant.f137,
                    ),

                    // indicatorColor: Colors.black,
                    // unselectedLabelColor: Colors.redAccent,
                    indicatorWeight: 0,
                    indicatorSize: TabBarIndicatorSize.label,
                    indicator: BoxDecoration(
                        color: const Color.fromRGBO(251, 66, 187, 1),
                        borderRadius: BorderRadius.circular(16.8),
                        border: Border.all(
                          color: const Color.fromRGBO(251, 66, 187, 1),
                          width: 0.9,
                        )),
                    dividerColor: Colors.transparent,
                    dividerHeight: 0,
                    splashBorderRadius: BorderRadius.circular(16.8),
                    labelPadding: const EdgeInsets.symmetric(
                        horizontal: 3.55, vertical: 0),
                    isScrollable: true,
                    tabs: List.generate(tabName.length, (index) {
                      return renderTab(
                          tabName[index], index == tabModal.activeIndex, index);
                    }),
                  ),
                ),
              )
            : Container(
                key: const ValueKey("home_tab_false"),
                height: widget.wrapperHeight,
                alignment: Alignment.center,
                child: Padding(
                  padding: const EdgeInsets.only(left: 10),
                  child: CrossScroll(
                      tabController: widget.homeTabController,
                      activeIndex: tabModal.activeIndex,
                      labelPadding: EdgeInsets.zero,
                      onTap: (int index) {
                        ref
                            .read(tabProvider.notifier)
                            .changeTab(index, tabName: tabName[index]);
                      },
                      child: (index) => Container(
                            padding: const EdgeInsets.only(top: 1),

                            ///tab之间默认间隔是8
                            width: 61 + (index == 0 ? (17.5 * 2 + 1) : 18) - 8,
                            child: Stack(
                              children: [
                                Visibility(
                                    visible: tabModal.activeIndex == index,
                                    child: Positioned(
                                      left: 61 / 2 - 13.5,
                                      bottom: 0,
                                      child: ImageLoader.imageNet(
                                          ImageConstant.homeTabSlide,
                                          width: 27,
                                          height: 11),
                                    )),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Column(
                                      children: [
                                        ImageLoader.imageAsset(imgList[index],
                                            hasRoot: false,
                                            height: 53,
                                            width: 53),
                                        SizedBox(
                                          width: 61,
                                          child: Padding(
                                            padding:
                                                const EdgeInsets.only(top: 5),
                                            child: Text(
                                              tabName[index],
                                              overflow: TextOverflow.ellipsis,
                                              maxLines: 2,
                                              textAlign: TextAlign.center,
                                              style: const TextStyle(
                                                  fontSize: 11,
                                                  color: Color(0xFF343434)),
                                            ),
                                          ),
                                        )
                                      ],
                                    ),
                                    if (index == 0)
                                      Container(
                                        width: 1,
                                        height: 36,
                                        margin: const EdgeInsets.only(
                                            top: 9, left: 17.5 - 8 / 2),
                                        color: const Color(0xFFE2E4E6),
                                      ),
                                  ],
                                )
                              ],
                            ),
                          ),
                      childLength: tabName.length),
                ),
              ));
  }
}
